package org.opportunity.api.lucene.toolkit.index;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

public abstract class IndexerManager {

    public static enum Indexer {
	TXT {
	   
	    @Override
	    boolean acceptFile(File file) {
		String filename = file.getName().toLowerCase();
		if(filename.endsWith(".txt") || filename.endsWith(".TXT")) {
		    return true;
		}
		return false;
		
	    }
	}, HTML{

	    @Override
	    boolean acceptFile(File file) {
		// TODO Auto-generated method stub
		return false;
	    }
	    
	    
	};
	
	abstract boolean acceptFile(File file);
    }

    static Logger logger = Logger.getLogger(IndexerManager.class);
    
    public static final String FIELD_PATH = "path";
    public static final String FIELD_CONTENTS = "contents";
    
    protected IndexWriter writer = null;
    protected List<File> queue = new ArrayList<File>();
    
    public abstract void index(String dataDir) throws IOException;

    protected boolean ifDirectoryExists(String dir) {
	File directory = new File(dir);
	if (0 < directory.length()) {
	    return true;

	} else {
	    return false;

	}
    }

    protected void addFiles(File file, Indexer indexer) {
	if (file.exists() && !file.isHidden() && file.canRead()) {
	    if (file.isDirectory()) {
		for (File f : file.listFiles()) {
		    addFiles(f, indexer);
		}

	    } else {
		if (indexer.acceptFile(file)) {
		    queue.add(file);
		    
		}
	    }
	}
    }
    
    protected void indexFile(File f) {
	Document doc;
	try {
	    doc = getDocument(f);
	    if(doc != null) {
		writer.addDocument(doc);
		logger.info("Added: " + f);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    logger.error("Could not add: " + f);
	}
    }
    
    protected Document getDocument(File f) throws Exception {
	Document doc = new Document();
	doc.add(new Field(FIELD_PATH, f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
	doc.add(new Field(FIELD_CONTENTS, new FileReader(f)));
	return doc;
	
    }

}
